{$MODE objfpc}
{$MACRO ON}

//
// Pascal mapping of the Object.h file
//

{ Object and type object interface

Objects are structures allocated on the heap.  Special rules apply to
the use of objects to ensure they are properly garbage-collected.
Objects are never allocated statically or on the stack; they must be
accessed through special macros and functions only.  (Type objects are
exceptions to the first rule; the standard types are represented by
statically initialized type objects, although work on type/class unification
for Python 2.2 made it possible to have heap-allocated type objects too).

An object has a 'reference count' that is increased or decreased when a
pointer to the object is copied or deleted; when the reference count
reaches zero there are no references to the object left and it can be
removed from the heap.

An object has a 'type' that determines what it represents and what kind
of data it contains.  An object's type is fixed when it is created.
Types themselves are represented as objects; an object contains a
pointer to the corresponding type object.  The type itself has a type
pointer pointing to the object representing the type 'type', which
contains a pointer to itself!).

Objects do not float around in memory; once allocated an object keeps
the same size and address.  Objects that must hold variable-size data
can contain pointers to variable-size parts of the object.  Not all
objects of the same type have the same size; but the size cannot change
after allocation.  (These restrictions are made so a reference to an
object can be simply a pointer -- moving an object would require
updating all the pointers, and changing an object's size would require
moving it if there was another object right next to it.)

Objects are always accessed through pointers of the type 'PyObjectPtr '.
The type 'PyObject' is a structure that only contains the reference count
and the type pointer.  The actual memory allocated for an object
contains other data that can only be accessed after casting the pointer
to a pointer to a longer structure type.  This longer type must start
with the reference count and type fields; the macro PyObject_HEAD should be
used for this (to accommodate for future changes).  The implementation
of a particular object type can cast the object pointer to the proper
type and back.

A standard interface exists for objects that contain an array of items
whose size is determined when the object is allocated.
}


unit PythonObject;

interface
uses PythonTypes, PythonMethodObject;

	var
		PyType_Type: PyTypeObject; cvar; external;        // built-in 'type'
		PyBaseObject_Type: PyTypeObject; cvar; external;  // built-in 'object'
		PySuper_Type: PyTypeObject; cvar; external;       // built-in 'super'

	// access macro to the members which are floating "behind" the object
	function PyHeapType_GET_MEMBERS(etype: PyHeapTypeObjectPtr): PyMemberDefPtr;

	// Generic type check
	function PyTypeIsSubtype(obj, obj1: PyTypeObjectPtr): Boolean;
	function PyType_IsSubtype(obj, obj1: PyTypeObjectPtr): Integer; cdecl; external; {$EXTERNALSYM PyType_IsSubtype}

	function PyObject_TypeCheck(ob: PyObjectPtr; tp: PyTypeObjectPtr) : Boolean;

	function PyType_Check(op: PyObjectPtr): Boolean;
	function PyType_CheckExact(op: PyObjectPtr): Boolean;

	function PyType_Ready(typ: PyTypeObjectPtr): Integer; cdecl; external; {$EXTERNALSYM PyType_Ready}
	
	function PyType_GenericAlloc(obj: PyTypeObjectPtr; sz: Py_ssize_t): PyObjectPtr; cdecl; external; {$EXTERNALSYM PyType_GenericAlloc}
	function PyType_GenericNew(typ: PyTypeObjectPtr; obj, obj1: PyObjectPtr): PyObjectPtr; cdecl; external; {$EXTERNALSYM PyType_GenericNew}
	function _PyType_Lookup(typ: PyTypeObjectPtr; obj: PyObjectPtr): PyObjectPtr; cdecl; external; {$EXTERNALSYM _PyType_Lookup}

	// Generic operations on objects
	function PyObject_Print(obj: PyObjectPtr; var output: FILE; int: Integer): Integer; cdecl; external; {$EXTERNALSYM PyObject_Print}
	procedure _PyObject_Dump(obj: PyObjectPtr); cdecl; external; {$EXTERNALSYM _PyObject_Dump}
	function  PyObject_Repr(obj: PyObjectPtr): PyObjectPtr; cdecl; external; {$EXTERNALSYM PyObject_Repr}
	function  _PyObject_Str(obj: PyObjectPtr): PyObjectPtr; cdecl; external; {$EXTERNALSYM _PyObject_Str}
	function  PyObject_Str(obj: PyObjectPtr): PyObjectPtr; cdecl; external; {$EXTERNALSYM PyObject_Str}

	//#ifdef Py_USING_UNICODE
	function PyObject_Unicode(obj: PyObjectPtr): PyObjectPtr; cdecl; external; {$EXTERNALSYM PyObject_Unicode}
	//#endif
	
  function PyObject_Compare(o1, o2: PyObjectPtr): Integer; cdecl; external; {$EXTERNALSYM PyObject_Compare}
  function PyObject_RichCompare(o1, o2: PyObjectPtr; int: Integer): PyObjectPtr; cdecl; external;
  function PyObject_RichCompareBool(o1, o2: PyObjectPtr; int: Integer): Integer; cdecl; external;
  function PyObject_GetAttrString(ob: PyObjectPtr; attr: PChar): PyObjectPtr; cdecl; external; //new reference
  function PyObject_SetAttrString(ob: PyObjectPtr; attr: PChar; val: PyObjectPtr): Integer; cdecl; external;
  function PyObject_HasAttrString(ob: PyObjectPtr; attr: PChar): Integer; cdecl; external;
  function PyObject_GetAttr(o1, o2: PyObjectPtr): PyObjectPtr; cdecl; external;
  function PyObject_SetAttr(o1, o2, o3: PyObjectPtr): Integer; cdecl; external;
  function PyObject_HasAttr(o1, o2: PyObjectPtr): Integer; cdecl; external;
  function _PyObject_GetDictPtr(ob: PyObjectPtr): PyObjectPtrPtr; cdecl; external;
  function PyObject_SelfIter(ob: PyObjectPtr): PyObjectPtr; cdecl; external;
  function PyObject_GenericGetAttr(ob1, ob2 :PyObjectPtr): PyObjectPtr; cdecl; external;
  function PyObject_GenericSetAttr(o1, o2, o3 :PyObjectPtr): Integer; cdecl; external;
  function PyObject_Hash(ob: PyObjectPtr): Int64; cdecl; external;
  function PyObject_IsTrue(ob: PyObjectPtr): Integer; cdecl; external;
  function PyObject_Not(ob: PyObjectPtr): Integer; cdecl; external;
  function PyCallable_Check(ob: PyObjectPtr ): Integer; cdecl; external;
  function PyNumber_Coerce(op1, op2: PyObjectPtrPtr): Integer; cdecl; external;
  function PyNumber_CoerceEx(op1, op2: PyObjectPtrPtr): Integer; cdecl; external;

  procedure PyObject_ClearWeakRefs(ob: PyObjectPtr); cdecl; external;

  // A slot function whose address we need to compare 
  function _PyObject_SlotCompare(ob1, ob2: PyObjectPtr): Integer; cdecl; external;
  
  // PyObject_Dir(obj) acts like Python __builtin__.dir(obj), returning a
  //   list of strings.  PyObject_Dir(NULL) is like __builtin__.dir(),
  //   returning the names of the current locals.  In this case, if there are
  //   no current locals, NULL is returned, and PyErr_Occurred() is false.
     
  function PyObject_Dir(ob: PyObjectPtr): PyObjectPtr; cdecl; external;

  // Helpers for printing recursive container types
  function Py_ReprEnter(ob: PyObjectPtr): Integer; cdecl; external;
  procedure Py_ReprLeave(ob: PyObjectPtr); cdecl; external;

  // Helpers for hash functions
  function _Py_HashDouble(d: Double): Int64; cdecl; external;
  function _Py_HashPointer(p: Pointer): Int64; cdecl; external;
  
  // The macros Py_INCREF(op) and Py_DECREF(op) are used to increment or decrement
  // reference counts.  Py_DECREF calls the object's deallocator function when
  // the refcount falls to 0; for
  // objects that don't contain references to other objects or heap memory
  // this can be the standard function free().  Both macros can be used
  // wherever a void expression is allowed.  The argument must not be a
  // NIL pointer.  If it may be NIL, use Py_XINCREF/Py_XDECREF instead.
  // The macro _Py_NewReference(op) initialize reference counts to 1, and
  // in special builds (Py_REF_DEBUG, Py_TRACE_REFS) performs additional
  // bookkeeping appropriate to the special build.
  // 
  // We assume that the reference count field can never overflow; this can
  // be proven when the size of the field is the same as the pointer size, so
  // we ignore the possibility.  Provided a C int is at least 32 bits (which
  // is implicitly assumed in many parts of this code), that's enough for
  // about 2**31 references to an object.
  // 
  // XXX The following became out of date in Python 2.2, but I'm not sure
  // XXX what the full truth is now.  Certainly, heap-allocated type objects
  // XXX can and should be deallocated.
  // Type objects should never be deallocated; the type pointer in an object
  // is not considered to be a reference to the type object, to save
  // complications in the deallocation function.  (This is actually a
  // decision that's up to the implementer of each new type so if you want,
  // you can count such references to the type object.)
  // 
  // *** WARNING*** The Py_DECREF macro must have a side-effect-free argument
  // since it may evaluate its argument multiple times.  (The alternative
  // would be to mace it a proper function or assign it to a global temporary
  // variable first, both of which are slower; and in a multi-threaded
  // environment the global variable trick is not safe.)

  // First define a pile of simple helper macros, one set per special
  // * build symbol.  These either expand to the obvious things, or to
  // * nothing at all when the special mode isn't in effect.  The main
  // * macros can later be defined just once then, yet expand to different
  // * things depending on which special build options are and aren't in effect.
  // * Trust me <wink>:  while painful, this is 20x easier to understand than,
  // * e.g, defining _Py_NewReference five different times in a maze of nested
  // * #ifdefs (we used to do that -- it was impenetrable).

  procedure _Py_NewReference(ob: PyObjectPtr); cdecl; external;
  procedure _Py_ForgetReference(ob: PyObjectPtr ); cdecl; external;
  procedure _Py_Dealloc(ob: PyObjectPtr); cdecl; external;
  procedure _Py_PrintReferences(var o: FILE); cdecl; external;
  procedure _Py_PrintReferenceAddresses(var o: FILE); cdecl; external;
  procedure _Py_AddToAllObjects(ob: PyObjectPtr; force: Integer); cdecl; external;
	
	
  // Safely decref `op` and set `op` to NULL, especially useful in tp_clear
   // * and tp_dealloc implementatons.
   // *
   // * Note that "the obvious" code can be deadly:
   // *
   // *     Py_XDECREF(op);
   // *     op = NULL;
   // *
   // * Typically, `op` is something like self->containee, and `self` is done
   // * using its `containee` member.  In the code sequence above, suppose
   // * `containee` is non-NULL with a refcount of 1.  Its refcount falls to
   // * 0 on the first line, which can trigger an arbitrary amount of code,
   // * possibly including finalizers (like __del__ methods or weakref callbacks)
   // * coded in Python, which in turn can release the GIL and allow other threads
   // * to run, etc.  Such code may even invoke methods of `self` again, or cause
   // * cyclic gc to trigger, but-- oops! --self->containee still points to the
   // * object being torn down, and it may be in an insane state while being torn
   // * down.  This has in fact been a rich historic source of miserable (rare &
   // * hard-to-diagnose) segfaulting (and other) bugs.
   // *
   // * The safe way is:
   // *
   // *      Py_CLEAR(op);
   // *
   // * That arranges to set `op` to NULL _before_ decref'ing, so that any code
   // * triggered as a side-effect of `op` getting torn down no longer believes
   // * `op` points to a valid object.
   // *
   // * There are cases where it's safe to use the naive code, but they're brittle.
   // * For example, if `op` points to a Python integer, you know that destroying
   // * one of those can't cause problems -- but in part that relies on that
   // * Python integers aren't currently weakly referencable.  Best practice is
   // * to use Py_CLEAR() even if you can't think of a reason for why you need to.
  procedure Py_CLEAR(var op: PyObjectPtr);

  // Macros to use in case the object pointer may be NULL: */
  procedure Py_XINCREF(op: PyObjectPtr);
  procedure Py_XDECREF(op: PyObjectPtr);

  //
  // These are provided as conveniences to Python runtime embedders, so that
  // they can have object code that is not dependent on Python compilation flags.
  //
  procedure Py_IncRef(ob: PyObjectPtr); cdecl; external;
  procedure Py_DecRef(ob: PyObjectPtr); cdecl; external;
    
  //
  // _Py_NoneStruct is an object of undefined type which can be used in contexts
  // where NULL (nil) is not suitable (since NULL often means 'error').
  //
  // Don't forget to apply Py_INCREF() when returning this value!!!
  //
  var _Py_NoneStruct: PyObject; cvar; external; // Don't use this directly */
      Py_None: PyObjectPtr = @_Py_NoneStruct;

  // Macro for returning Py_None from a function */
  {$DEFINE Py_RETURN_NONE:=result := Py_None; Py_INCREF(Py_None)}
  
  
  //
  // Py_NotImplemented is a singleton used to signal that an operation is
  // not implemented for a given type combination.
  //
  var _Py_NotImplementedStruct: PyObject; cvar; external; // Don't use this directly */
      Py_NotImplemented: PyObjectPtr = @_Py_NotImplementedStruct;

  const
    // Rich comparison opcodes */
    Py_LT = 0;
    Py_LE = 1;
    Py_EQ = 2;
    Py_NE = 3;
    Py_GT = 4;
    Py_GE = 5;

  // Maps Py_LT to Py_GT, ..., Py_GE to Py_LE.
  // Defined in object.c.
  //
  var _Py_SwappedOp: Array of Integer; cvar; external;

  const
    // Flag bits for printing:
    Py_PRINT_RAW = 1;	// No string quotes etc.

    // `Type flags (tp_flags)
    // 
    // These flags are used to extend the type structure in a backwards-compatible
    // fashion. Extensions can use the flags to indicate (and test) when a given
    // type structure contains a new feature. The Python core will use these when
    // introducing new functionality between major revisions (to avoid mid-version
    // changes in the PYTHON_API_VERSION).
    // 
    // Arbitration of the flag bit positions will need to be coordinated among
    // all extension writers who publically release their extensions (this will
    // be fewer than you might expect!)..
    // 
    // Python 1.5.2 introduced the bf_getcharbuffer slot into PyBufferProcs.
    // 
    // Type definitions should use Py_TPFLAGS_DEFAULT for their tp_flags value.
    // 
    // Code can use PyType_HasFeature(type_ob, flag_value) to test whether the
    // given type object has a specified feature.

    // PyBufferProcs contains bf_getcharbuffer
    Py_TPFLAGS_HAVE_GETCHARBUFFER : Long = Long(1) shl 0; {$EXTERNALSYM Py_TPFLAGS_HAVE_GETCHARBUFFER}

    // PySequenceMethods contains sq_contains */
    Py_TPFLAGS_HAVE_SEQUENCE_IN : Long = Long(1) shl 1; {$EXTERNALSYM Py_TPFLAGS_HAVE_SEQUENCE_IN}

    // This is here for backwards compatibility.  Extensions that use the old GC
    // API will still compile but the objects will not be tracked by the GC. */
    Py_TPFLAGS_GC = 0; // used to be : Long = Long(1) shl 2) */

    // PySequenceMethods and PyNumberMethods contain in-place operators */
    Py_TPFLAGS_HAVE_INPLACEOPS : Long = Long(1) shl 3;

    // PyNumberMethods do their own coercion */
    Py_TPFLAGS_CHECKTYPES : Long = Long(1) shl 4;

    // tp_richcompare is defined */
    Py_TPFLAGS_HAVE_RICHCOMPARE : Long = Long(1) shl 5;

    // Objects which are weakly referencable if their tp_weaklistoffset is >0 */
    Py_TPFLAGS_HAVE_WEAKREFS : Long = Long(1) shl 6;

    // tp_iter is defined */
    Py_TPFLAGS_HAVE_ITER : Long = Long(1) shl 7;

    // New members introduced by Python 2.2 exist */
    Py_TPFLAGS_HAVE_CLASS : Long = Long(1) shl 8;

    // Set if the type object is dynamically allocated */
    Py_TPFLAGS_HEAPTYPE : Long = Long(1) shl 9;

    // Set if the type allows subclassing */
    Py_TPFLAGS_BASETYPE : Long = Long(1) shl 10;

    // Set if the type is 'ready' -- fully initialized */
    Py_TPFLAGS_READY : Long = Long(1) shl 12;

    // Set while the type is being 'readied', to prevent recursive ready calls */
    Py_TPFLAGS_READYING : Long = Long(1) shl 13;

    // Objects support garbage collection (see objimp.h) */
    Py_TPFLAGS_HAVE_GC : Long = Long(1) shl 14;

    Py_TPFLAGS_HAVE_STACKLESS_EXTENSION = 0;

    // Objects support nb_index in PyNumberMethods */
    Py_TPFLAGS_HAVE_INDEX : Long = Long(1) shl 17;

    {Py_TPFLAGS_DEFAULT = Py_TPFLAGS_HAVE_GETCHARBUFFER or
                         Py_TPFLAGS_HAVE_SEQUENCE_IN or
                         Py_TPFLAGS_HAVE_INPLACEOPS or
                         Py_TPFLAGS_HAVE_RICHCOMPARE or
                         Py_TPFLAGS_HAVE_WEAKREFS or
                         Py_TPFLAGS_HAVE_ITER or
                         Py_TPFLAGS_HAVE_CLASS or
                         Py_TPFLAGS_HAVE_STACKLESS_EXTENSION or
                         Py_TPFLAGS_HAVE_INDEX;}


implementation

	function PyHeapType_GET_MEMBERS(etype: PyHeapTypeObjectPtr): PyMemberDefPtr;
	begin
		result := PyMemberDefPtr(etype + etype^.ht_type.ob_type^.tp_basicsize);
	end;

	function PyObject_TypeCheck(ob: PyObjectPtr; tp: PyTypeObjectPtr) : Boolean;
	begin
		result := (ob^.ob_type = tp) or PyTypeIsSubtype(ob^.ob_type, tp);
	end;

	function PyTypeIsSubtype(obj, obj1: PyTypeObjectPtr): Boolean;
	begin
		result := PyType_IsSubtype(obj, obj1) <> 0;
	end;

	function PyType_Check(op: PyObjectPtr): Boolean;
	begin
		result := PyObject_TypeCheck(op, @PyType_Type);
	end;

	function PyType_CheckExact(op: PyObjectPtr): Boolean;
	begin
		result := op^.ob_type = @PyType_Type;
	end;

  procedure Py_CLEAR(var op: PyObjectPtr);
  var
    tmp: PyObjectPtr;
  begin
    if (op <> nil) then
    begin
      tmp := op;
      op := nil;
      Py_DECREF(tmp);
    end;
  end;
  
  procedure Py_XINCREF(op: PyObjectPtr);
  begin
    if op <> nil then Py_INCREF(op);
  end;
  
  procedure Py_XDECREF(op: PyObjectPtr);
  begin
    if op <> nil then Py_DECREF(op);
  end;

	
end.

